package com.smartao.core.init;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartao.core.SpringContext;
import com.smartao.core.config.ConfigHolder;
import com.smartao.core.config.ConfigLoader;

public class PostServerInitListener implements ServletContextListener {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("Data Initializing...");
		Map<String, DataInitializeService> serviceMap = SpringContext.getBeans(DataInitializeService.class);
		Collection<DataInitializeService> collection = serviceMap.values();
		List<DataInitializeService> list = new ArrayList<DataInitializeService>();

		for (DataInitializeService service : collection) {
			list.add(service);
		}
		//按执行顺序排序
		Collections.sort(list);

		try {
			for (DataInitializeService service : list) {
				service.initData();
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		//初始化系统配置
		ConfigLoader configLoader = SpringContext.getBean(ConfigLoader.class);
		if (configLoader != null) {
			HashMap<String,String> properties = configLoader.loadConfigs();
			ConfigHolder.getInstance().initProperties(properties);
		}

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}
